package org.csu.mypetstore.service;

import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.LineItem;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.domain.Sequence;
import org.csu.mypetstore.persistence.*;
import org.csu.mypetstore.persistence.Impl.ItemDAOImpl;
import org.csu.mypetstore.persistence.Impl.LineItemDAOImpl;
import org.csu.mypetstore.persistence.Impl.OrderDAOImpl;
import org.csu.mypetstore.persistence.Impl.SequenceDAOImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderService{
  private ItemDAO itemDAO;
  private OrderDAO orderDAO;
  private SequenceDAO sequenceDAO;
  private LineItemDAO lineItemDAO;

  public OrderService(){
    itemDAO = new ItemDAOImpl();
    orderDAO = new OrderDAOImpl();
    sequenceDAO = new SequenceDAOImpl();
    lineItemDAO = new LineItemDAOImpl();
  }

  public int getNextId(String name){//name为line/ordernum

    Sequence sequence = new Sequence(name,-1);
    sequence = sequenceDAO.getSequence(sequence);//去数据库查询，看是否存在订单，不存在新建，存在则继续计数
    if(sequence == null){
      throw new RuntimeException("Error: A null sequence was returned from the database (could not get next  " + name +
              " sequence).");//抛出异常显示在浏览器错误页面中
    }
    Sequence parameterObject = new Sequence(name,sequence.getNextId()+1);
    sequenceDAO.updateSequence(parameterObject);
    return sequence.getNextId();
  }

  public void insertOrder(Order order) {
    order.setOrderId(getNextId("ordernum"));//注明是更新订单列表的
    //更新数据库中的库存inventory
    for(int i=0;i<order.getLineItems().size();i++){
      LineItem lineItem = order.getLineItems().get(i);
      String itemId = lineItem.getItemId();
      Integer increment = new Integer(lineItem.getQuantity());
      Map<String,Object> param = new HashMap<String,Object>(2);
      param.put("itemId",itemId);//键值对
      param.put("increment",increment);
      itemDAO.updateInventoryQuantity(param);
    }
    orderDAO.insertOrder(order);//订单信息存入数据库中
    orderDAO.insertOrderStatus(order);//修改订单状态
    for(int i=0;i<order.getLineItems().size();i++){
      LineItem lineItem = order.getLineItems().get(i);
      lineItem.setOrderId(order.getOrderId());
      lineItemDAO.insertLineItem(lineItem);//把订单商品加入数据库
    }
  }

  public Order getOrder(int orderId){
    Order order = orderDAO.getOrder(orderId);//获取订单信息
    order.setLineItems(lineItemDAO.getLineItemsByOrderId(orderId));//获取该订单的商品属性

    for(int i=0;i<order.getLineItems().size();i++){
      LineItem lineItem = (LineItem) order.getLineItems().get(i);
      Item item = itemDAO.getItem(lineItem.getItemId());
      item.setQuantity(itemDAO.getInventoryQuantity(lineItem.getItemId()));
      lineItem.setItem(item);
    }
    return order;
  }

  public List<Order> getOrdersByUsername(String username){
    return orderDAO.getOrdersByUsername(username);
  }

}
